%%%-------------------------------------------------------------------
%%% @author mirahs(2892727493@qq.com)
%%% @doc
%%%     角色通讯数据拦截器
%%% @end
%%%-------------------------------------------------------------------
-module(role_send_buffer_ic).

-export([
    rpc_before/3
    ,rpc_after_success/4
    ,rpc_after_fail/3
]).

-include("common.hrl").
-include("role.hrl").


%% rpc_before(RpcCfg, Rpc, Role) -> true | false
%% Rpc = {rpc, Cmd, Data} | {mfa, {M, F, A}}
%% Role = #role{}
%% rpc 前置处理
rpc_before(#rpc_cfg{send_buff = true}, _Rpc, _Role) ->
    buffer_begin(),
    true;
rpc_before(_, _, _) ->
    true.

%% rpc_after_success(RpcCfg, Data, Role, NewRole) -> NewRole2
%% Data = {rpc, Cmd, Data} | {mfa, {M, F, A}}
%% Role = NewRole = #role{}
%% rpc 成功后处理
rpc_after_success(_RpcConfig = #rpc_cfg{send_buff = true}, _Data, _Role, NewRole) ->
    buffer_flush(),
    NewRole;
rpc_after_success(_, _, _Role, NewRole) ->
    NewRole.

%% rpc_after_fail(RpcCfg, Rpc, Role) -> ok
%% Rpc = {rpc, Cmd, Data} | {mfa, {M, F, A}}
%% Role = #role{}
%% rpc失败后处理
rpc_after_fail(#rpc_cfg{send_buff = true}, _Rpc, _Role) ->
    buffer_clean(),
    ok;
rpc_after_fail(_, _, _Role) ->
    ok.


buffer_begin() ->
    put(send_buffer, []).

buffer_flush() ->
    case get(send_buffer) of
        Bins = [_|_] ->
            get(conn_pid) ! {send, lists:reverse(Bins)},
            put(send_buffer, undefined);
        _ -> ok
    end.

buffer_clean() ->
    put(send_buffer, undefined).
